1. Project Clover database Mon Aug 8 2022 22:37:39 MDT
  2. Package org.joda.time

File DateTimeUtils.java

 

Coverage histogram

../../../img/srcFileCovDistChart10.png
0% of files have more coverage

Code metrics

40
97
30
5
584
206
53
0.55
3.23
6
1.77

Classes

Class Line # Actions
DateTimeUtils 38 92 0% 48 9
0.942675294.3%
DateTimeUtils.MillisProvider 512 0 - 0 0
-1.0 -
DateTimeUtils.SystemMillisProvider 526 1 0% 1 0
1.0100%
DateTimeUtils.FixedMillisProvider 539 2 0% 2 0
1.0100%
DateTimeUtils.OffsetMillisProvider 563 2 0% 2 0
1.0100%
 

Contributing tests

This file is covered by 3125 tests. .

Source view

1    /*
2    * Copyright 2001-2013 Stephen Colebourne
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10    * Unless required by applicable law or agreed to in writing, software
11    * distributed under the License is distributed on an "AS IS" BASIS,
12    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13    * See the License for the specific language governing permissions and
14    * limitations under the License.
15    */
16    package org.joda.time;
17   
18    import java.lang.reflect.Method;
19    import java.text.DateFormatSymbols;
20    import java.util.Collections;
21    import java.util.HashMap;
22    import java.util.LinkedHashMap;
23    import java.util.Locale;
24    import java.util.Map;
25   
26    import org.joda.time.chrono.ISOChronology;
27   
28    /**
29    * DateTimeUtils provide public utility methods for the date-time library.
30    * <p>
31    * DateTimeUtils uses shared static variables which are declared as volatile
32    * for thread-safety. These can be changed during the lifetime of the application
33    * however doing so is generally a bad idea.
34    *
35    * @author Stephen Colebourne
36    * @since 1.0
37    */
 
38    public class DateTimeUtils {
39   
40    /** The singleton instance of the system millisecond provider. */
41    private static final SystemMillisProvider SYSTEM_MILLIS_PROVIDER = new SystemMillisProvider();
42    /** The millisecond provider currently in use. */
43    private static volatile MillisProvider cMillisProvider = SYSTEM_MILLIS_PROVIDER;
44    /** The millisecond provider currently in use. */
45    private static volatile Map<String, DateTimeZone> cZoneNames;
 
46  2 toggle static {
47    // names from RFC-822 / JDK
48    // this is all very US-centric and dubious, but perhaps it will help some
49  2 Map<String, DateTimeZone> map = new LinkedHashMap<String, DateTimeZone>();
50  2 map.put("UT", DateTimeZone.UTC);
51  2 map.put("UTC", DateTimeZone.UTC);
52  2 map.put("GMT", DateTimeZone.UTC);
53  2 put(map, "EST", "America/New_York");
54  2 put(map, "EDT", "America/New_York");
55  2 put(map, "CST", "America/Chicago");
56  2 put(map, "CDT", "America/Chicago");
57  2 put(map, "MST", "America/Denver");
58  2 put(map, "MDT", "America/Denver");
59  2 put(map, "PST", "America/Los_Angeles");
60  2 put(map, "PDT", "America/Los_Angeles");
61  2 cZoneNames = Collections.unmodifiableMap(map);
62    }
 
63  16 toggle private static void put(Map<String, DateTimeZone> map, String name, String id) {
64  16 try {
65  16 map.put(name, DateTimeZone.forID(id));
66    } catch (RuntimeException ex) {
67    // ignore
68    }
69    }
70   
71    /**
72    * Restrictive constructor
73    */
 
74  1 toggle protected DateTimeUtils() {
75  1 super();
76    }
77   
78    //-----------------------------------------------------------------------
79    /**
80    * Gets the current time in milliseconds.
81    * <p>
82    * By default this returns <code>System.currentTimeMillis()</code>.
83    * This may be changed using other methods in this class.
84    *
85    * @return the current time in milliseconds from 1970-01-01T00:00:00Z
86    */
 
87  610 toggle public static final long currentTimeMillis() {
88  610 return cMillisProvider.getMillis();
89    }
90   
91    /**
92    * Resets the current time to return the system time.
93    * <p>
94    * This method changes the behaviour of {@link #currentTimeMillis()}.
95    * Whenever the current time is queried, {@link System#currentTimeMillis()} is used.
96    *
97    * @throws SecurityException if the application does not have sufficient security rights
98    */
 
99  2868 toggle public static final void setCurrentMillisSystem() throws SecurityException {
100  2868 checkPermission();
101  2868 cMillisProvider = SYSTEM_MILLIS_PROVIDER;
102    }
103   
104    /**
105    * Sets the current time to return a fixed millisecond time.
106    * <p>
107    * This method changes the behaviour of {@link #currentTimeMillis()}.
108    * Whenever the current time is queried, the same millisecond time will be returned.
109    *
110    * @param fixedMillis the fixed millisecond time to use
111    * @throws SecurityException if the application does not have sufficient security rights
112    */
 
113  2999 toggle public static final void setCurrentMillisFixed(long fixedMillis) throws SecurityException {
114  2999 checkPermission();
115  2999 cMillisProvider = new FixedMillisProvider(fixedMillis);
116    }
117   
118    /**
119    * Sets the current time to return the system time plus an offset.
120    * <p>
121    * This method changes the behaviour of {@link #currentTimeMillis()}.
122    * Whenever the current time is queried, {@link System#currentTimeMillis()} is used
123    * and then offset by adding the millisecond value specified here.
124    *
125    * @param offsetMillis the fixed millisecond time to use
126    * @throws SecurityException if the application does not have sufficient security rights
127    */
 
128  1 toggle public static final void setCurrentMillisOffset(long offsetMillis) throws SecurityException {
129  1 checkPermission();
130  1 if (offsetMillis == 0) {
131  0 cMillisProvider = SYSTEM_MILLIS_PROVIDER;
132    } else {
133  1 cMillisProvider = new OffsetMillisProvider(offsetMillis);
134    }
135    }
136   
137    /**
138    * Sets the provider of the current time to class specified.
139    * <p>
140    * This method changes the behaviour of {@link #currentTimeMillis()}.
141    * Whenever the current time is queried, the specified class will be called.
142    *
143    * @param millisProvider the provider of the current time to use, not null
144    * @throws SecurityException if the application does not have sufficient security rights
145    * @since 2.0
146    */
 
147  2 toggle public static final void setCurrentMillisProvider(MillisProvider millisProvider) throws SecurityException {
148  2 if (millisProvider == null) {
149  1 throw new IllegalArgumentException("The MillisProvider must not be null");
150    }
151  1 checkPermission();
152  1 cMillisProvider = millisProvider;
153    }
154   
155    /**
156    * Checks whether the provider may be changed using permission 'CurrentTime.setProvider'.
157    *
158    * @throws SecurityException if the provider may not be changed
159    */
 
160  5869 toggle private static void checkPermission() throws SecurityException {
161  5869 SecurityManager sm = System.getSecurityManager();
162  5869 if (sm != null) {
163  0 sm.checkPermission(new JodaTimePermission("CurrentTime.setProvider"));
164    }
165    }
166   
167    //-----------------------------------------------------------------------
168    /**
169    * Gets the millisecond instant from the specified instant object handling null.
170    * <p>
171    * If the instant object is <code>null</code>, the {@link #currentTimeMillis()}
172    * will be returned. Otherwise, the millis from the object are returned.
173    *
174    * @param instant the instant to examine, null means now
175    * @return the time in milliseconds from 1970-01-01T00:00:00Z
176    */
 
177  4177 toggle public static final long getInstantMillis(ReadableInstant instant) {
178  4177 if (instant == null) {
179  82 return DateTimeUtils.currentTimeMillis();
180    }
181  4095 return instant.getMillis();
182    }
183   
184    //-----------------------------------------------------------------------
185    /**
186    * Gets the chronology from the specified instant object handling null.
187    * <p>
188    * If the instant object is <code>null</code>, or the instant's chronology is
189    * <code>null</code>, {@link ISOChronology#getInstance()} will be returned.
190    * Otherwise, the chronology from the object is returned.
191    *
192    * @param instant the instant to examine, null means ISO in the default zone
193    * @return the chronology, never null
194    */
 
195  3858 toggle public static final Chronology getInstantChronology(ReadableInstant instant) {
196  3858 if (instant == null) {
197  29 return ISOChronology.getInstance();
198    }
199  3829 Chronology chrono = instant.getChronology();
200  3829 if (chrono == null) {
201  1 return ISOChronology.getInstance();
202    }
203  3828 return chrono;
204    }
205   
206    //-----------------------------------------------------------------------
207    /**
208    * Gets the chronology from the specified instant based interval handling null.
209    * <p>
210    * The chronology is obtained from the start if that is not null, or from the
211    * end if the start is null. The result is additionally checked, and if still
212    * null then {@link ISOChronology#getInstance()} will be returned.
213    *
214    * @param start the instant to examine and use as the primary source of the chronology
215    * @param end the instant to examine and use as the secondary source of the chronology
216    * @return the chronology, never null
217    */
 
218  37 toggle public static final Chronology getIntervalChronology(ReadableInstant start, ReadableInstant end) {
219  37 Chronology chrono = null;
220  37 if (start != null) {
221  31 chrono = start.getChronology();
222  6 } else if (end != null) {
223  5 chrono = end.getChronology();
224    }
225  37 if (chrono == null) {
226  1 chrono = ISOChronology.getInstance();
227    }
228  37 return chrono;
229    }
230   
231    //-----------------------------------------------------------------------
232    /**
233    * Gets the chronology from the specified interval object handling null.
234    * <p>
235    * If the interval object is <code>null</code>, or the interval's chronology is
236    * <code>null</code>, {@link ISOChronology#getInstance()} will be returned.
237    * Otherwise, the chronology from the object is returned.
238    *
239    * @param interval the interval to examine, null means ISO in the default zone
240    * @return the chronology, never null
241    */
 
242  4 toggle public static final Chronology getIntervalChronology(ReadableInterval interval) {
243  4 if (interval == null) {
244  1 return ISOChronology.getInstance();
245    }
246  3 Chronology chrono = interval.getChronology();
247  3 if (chrono == null) {
248  1 return ISOChronology.getInstance();
249    }
250  2 return chrono;
251    }
252   
253    //-----------------------------------------------------------------------
254    /**
255    * Gets the interval handling null.
256    * <p>
257    * If the interval is <code>null</code>, an interval representing now
258    * to now in the {@link ISOChronology#getInstance() ISOChronology}
259    * will be returned. Otherwise, the interval specified is returned.
260    *
261    * @param interval the interval to use, null means now to now
262    * @return the interval, never null
263    * @since 1.1
264    */
 
265  86 toggle public static final ReadableInterval getReadableInterval(ReadableInterval interval) {
266  86 if (interval == null) {
267  14 long now = DateTimeUtils.currentTimeMillis();
268  14 interval = new Interval(now, now);
269    }
270  86 return interval;
271    }
272   
273    //-----------------------------------------------------------------------
274    /**
275    * Gets the chronology handling null.
276    * <p>
277    * If the chronology is <code>null</code>, {@link ISOChronology#getInstance()}
278    * will be returned. Otherwise, the chronology is returned.
279    *
280    * @param chrono the chronology to use, null means ISO in the default zone
281    * @return the chronology, never null
282    */
 
283  442674 toggle public static final Chronology getChronology(Chronology chrono) {
284  442674 if (chrono == null) {
285  6230 return ISOChronology.getInstance();
286    }
287  436444 return chrono;
288    }
289   
290    //-----------------------------------------------------------------------
291    /**
292    * Gets the zone handling null.
293    * <p>
294    * If the zone is <code>null</code>, {@link DateTimeZone#getDefault()}
295    * will be returned. Otherwise, the zone specified is returned.
296    *
297    * @param zone the time zone to use, null means the default zone
298    * @return the time zone, never null
299    */
 
300  30072 toggle public static final DateTimeZone getZone(DateTimeZone zone) {
301  30072 if (zone == null) {
302  33 return DateTimeZone.getDefault();
303    }
304  30039 return zone;
305    }
306   
307    //-----------------------------------------------------------------------
308    /**
309    * Gets the period type handling null.
310    * <p>
311    * If the zone is <code>null</code>, {@link PeriodType#standard()}
312    * will be returned. Otherwise, the type specified is returned.
313    *
314    * @param type the time zone to use, null means the standard type
315    * @return the type to use, never null
316    */
 
317  34372 toggle public static final PeriodType getPeriodType(PeriodType type) {
318  34372 if (type == null) {
319  153 return PeriodType.standard();
320    }
321  34219 return type;
322    }
323   
324    //-----------------------------------------------------------------------
325    /**
326    * Gets the millisecond duration from the specified duration object handling null.
327    * <p>
328    * If the duration object is <code>null</code>, zero will be returned.
329    * Otherwise, the millis from the object are returned.
330    *
331    * @param duration the duration to examine, null means zero
332    * @return the duration in milliseconds
333    */
 
334  65 toggle public static final long getDurationMillis(ReadableDuration duration) {
335  65 if (duration == null) {
336  22 return 0L;
337    }
338  43 return duration.getMillis();
339    }
340   
341    //-----------------------------------------------------------------------
342    /**
343    * Checks whether the partial is contiguous.
344    * <p>
345    * A partial is contiguous if one field starts where another ends.
346    * <p>
347    * For example <code>LocalDate</code> is contiguous because DayOfMonth has
348    * the same range (Month) as the unit of the next field (MonthOfYear), and
349    * MonthOfYear has the same range (Year) as the unit of the next field (Year).
350    * <p>
351    * Similarly, <code>LocalTime</code> is contiguous, as it consists of
352    * MillisOfSecond, SecondOfMinute, MinuteOfHour and HourOfDay (note how
353    * the names of each field 'join up').
354    * <p>
355    * However, a Year/HourOfDay partial is not contiguous because the range
356    * field Day is not equal to the next field Year.
357    * Similarly, a DayOfWeek/DayOfMonth partial is not contiguous because
358    * the range Month is not equal to the next field Day.
359    *
360    * @param partial the partial to check
361    * @return true if the partial is contiguous
362    * @throws IllegalArgumentException if the partial is null
363    * @since 1.1
364    */
 
365  216 toggle public static final boolean isContiguous(ReadablePartial partial) {
366  216 if (partial == null) {
367  2 throw new IllegalArgumentException("Partial must not be null");
368    }
369  214 DurationFieldType lastType = null;
370  805 for (int i = 0; i < partial.size(); i++) {
371  600 DateTimeField loopField = partial.getField(i);
372  600 if (i > 0) {
373  386 if (loopField.getRangeDurationField() == null || loopField.getRangeDurationField().getType() != lastType) {
374  9 return false;
375    }
376    }
377  591 lastType = loopField.getDurationField().getType();
378    }
379  205 return true;
380    }
381   
382    //-----------------------------------------------------------------------
383    /**
384    * Gets the {@link DateFormatSymbols} based on the given locale.
385    * <p>
386    * If JDK 6 or newer is being used, DateFormatSymbols.getInstance(locale) will
387    * be used in order to allow the use of locales defined as extensions.
388    * Otherwise, new DateFormatSymbols(locale) will be used.
389    * See JDK 6 {@link DateFormatSymbols} for further information.
390    *
391    * @param locale the {@link Locale} used to get the correct {@link DateFormatSymbols}
392    * @return the symbols
393    * @since 2.0
394    */
 
395  13 toggle public static final DateFormatSymbols getDateFormatSymbols(Locale locale) {
396  13 try {
397  13 Method method = DateFormatSymbols.class.getMethod("getInstance", new Class[] {Locale.class});
398  13 return (DateFormatSymbols) method.invoke(null, new Object[] {locale});
399    } catch (Exception ex) {
400  0 return new DateFormatSymbols(locale);
401    }
402    }
403   
404    //-----------------------------------------------------------------------
405    /**
406    * Gets the default map of time zone names.
407    * <p>
408    * This can be changed by {@link #setDefaultTimeZoneNames}.
409    * <p>
410    * The default set of short time zone names is as follows:
411    * <ul>
412    * <li>UT - UTC
413    * <li>UTC - UTC
414    * <li>GMT - UTC
415    * <li>EST - America/New_York
416    * <li>EDT - America/New_York
417    * <li>CST - America/Chicago
418    * <li>CDT - America/Chicago
419    * <li>MST - America/Denver
420    * <li>MDT - America/Denver
421    * <li>PST - America/Los_Angeles
422    * <li>PDT - America/Los_Angeles
423    * </ul>
424    *
425    * @return the unmodifiable map of abbreviations to zones, not null
426    * @since 2.2
427    */
 
428  0 toggle public static final Map<String, DateTimeZone> getDefaultTimeZoneNames() {
429  0 return cZoneNames;
430    }
431   
432    /**
433    * Sets the default map of time zone names.
434    * <p>
435    * The map is copied before storage.
436    *
437    * @param names the map of abbreviations to zones, not null
438    * @since 2.2
439    */
 
440  0 toggle public static final void setDefaultTimeZoneNames(Map<String, DateTimeZone> names) {
441  0 cZoneNames = Collections.unmodifiableMap(new HashMap<String, DateTimeZone>(names));
442    }
443   
444    //-------------------------------------------------------------------------
445    /**
446    * Calculates the astronomical Julian Day for an instant.
447    * <p>
448    * The <a href="http://en.wikipedia.org/wiki/Julian_day">Julian day</a> is a well-known
449    * system of time measurement for scientific use by the astronomy community.
450    * It expresses the interval of time in days and fractions of a day since
451    * January 1, 4713 BC (Julian) Greenwich noon.
452    * <p>
453    * Each day starts at midday (not midnight) and time is expressed as a fraction.
454    * Thus the fraction 0.25 is 18:00. equal to one quarter of the day from midday to midday.
455    * <p>
456    * Note that this method has nothing to do with the day-of-year.
457    *
458    * @param epochMillis the epoch millis from 1970-01-01Z
459    * @return the astronomical Julian Day represented by the specified instant
460    * @since 2.2
461    */
 
462  16 toggle public static final double toJulianDay(long epochMillis) {
463    // useful links
464    // http://en.wikipedia.org/wiki/Julian_day#cite_note-13 - Wikipedia
465    // http://aa.usno.navy.mil/data/docs/JulianDate.php" - USNO
466    // http://users.zoominternet.net/~matto/Java/Julian%20Date%20Converter.htm - Julian Date Converter by Matt Oltersdorf
467    // http://ssd.jpl.nasa.gov/tc.cgi#top - CalTech
468  16 double epochDay = epochMillis / 86400000d;
469  16 return epochDay + 2440587.5d;
470    }
471   
472    /**
473    * Calculates the astronomical Julian Day Number for an instant.
474    * <p>
475    * The {@link #toJulianDay(long)} method calculates the astronomical Julian Day
476    * with a fraction based on days starting at midday.
477    * This method calculates the variant where days start at midnight.
478    * JDN 0 is used for the date equivalent to Monday January 1, 4713 BC (Julian).
479    * Thus these days start 12 hours before those of the fractional Julian Day.
480    * <p>
481    * Note that this method has nothing to do with the day-of-year.
482    *
483    * @param epochMillis the epoch millis from 1970-01-01Z
484    * @return the astronomical Julian Day represented by the specified instant
485    * @since 2.2
486    */
 
487  8 toggle public static final long toJulianDayNumber(long epochMillis) {
488  8 return (long) Math.floor(toJulianDay(epochMillis) + 0.5d);
489    }
490   
491    /**
492    * Creates a date-time from a Julian Day.
493    * <p>
494    * Returns the {@code DateTime} object equal to the specified Julian Day.
495    *
496    * @param julianDay the Julian Day
497    * @return the epoch millis from 1970-01-01Z
498    * @since 2.2
499    */
 
500  7 toggle public static final long fromJulianDay(double julianDay) {
501  7 double epochDay = julianDay - 2440587.5d;
502  7 return (long) (epochDay * 86400000d);
503    }
504   
505    //-----------------------------------------------------------------------
506    /**
507    * A millisecond provider, allowing control of the system clock.
508    *
509    * @author Stephen Colebourne
510    * @since 2.0 (previously private)
511    */
 
512    public static interface MillisProvider {
513    /**
514    * Gets the current time.
515    * <p>
516    * Implementations of this method must be thread-safe.
517    *
518    * @return the current time in milliseconds
519    */
520    long getMillis();
521    }
522   
523    /**
524    * System millis provider.
525    */
 
526    static class SystemMillisProvider implements MillisProvider {
527    /**
528    * Gets the current time.
529    * @return the current time in millis
530    */
 
531  131 toggle public long getMillis() {
532  131 return System.currentTimeMillis();
533    }
534    }
535   
536    /**
537    * Fixed millisecond provider.
538    */
 
539    static class FixedMillisProvider implements MillisProvider {
540    /** The fixed millis value. */
541    private final long iMillis;
542   
543    /**
544    * Constructor.
545    * @param offsetMillis the millis offset
546    */
 
547  2999 toggle FixedMillisProvider(long fixedMillis) {
548  2999 iMillis = fixedMillis;
549    }
550   
551    /**
552    * Gets the current time.
553    * @return the current time in millis
554    */
 
555  477 toggle public long getMillis() {
556  477 return iMillis;
557    }
558    }
559   
560    /**
561    * Offset from system millis provider.
562    */
 
563    static class OffsetMillisProvider implements MillisProvider {
564    /** The millis offset. */
565    private final long iMillis;
566   
567    /**
568    * Constructor.
569    * @param offsetMillis the millis offset
570    */
 
571  1 toggle OffsetMillisProvider(long offsetMillis) {
572  1 iMillis = offsetMillis;
573    }
574   
575    /**
576    * Gets the current time.
577    * @return the current time in millis
578    */
 
579  1 toggle public long getMillis() {
580  1 return System.currentTimeMillis() + iMillis;
581    }
582    }
583   
584    }